package it.uniroma2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;

public class HttpClient {

	private final String FILTER = "1";	

	public  String getDestinationUrl(String url) {
		PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
		cm.setMaxTotal(10);
		String destinationUrl = null;
		DefaultHttpClient client = new DefaultHttpClient(cm);
	
		try {
			HttpPost post = new HttpPost(url);
			
			HttpResponse response = client.execute(post);
			
				if (response.getStatusLine().getStatusCode() == 302){
					destinationUrl = response.getFirstHeader("Location").getValue();
				}	
	
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			client.getConnectionManager().shutdown();
		}
		return destinationUrl;
	}

	
	public  void upload(String location, File uploadFile) {

		PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
		cm.setMaxTotal(10);
		DefaultHttpClient client = new DefaultHttpClient(cm);
		HttpPost post = new HttpPost(location);
		try {
			MultipartEntity entity = new MultipartEntity();
			//filter is always 
			entity.addPart("filter", new StringBody(FILTER, "text/plain",
					Charset.forName("UTF-8")));

			entity.addPart("file", new FileBody(uploadFile));
			post.setEntity(entity);

			HttpResponse response = client.execute(post);
			
			if(response.getStatusLine().getStatusCode() == 200)
				System.out.print(".");
			else
				System.out.print(response.getStatusLine().getStatusCode());

			//if app returns image
//			File newf = new File(System.getenv("HOME")+"/"+ UUID.randomUUID().toString() + ".png");
//			BufferedInputStream br = new BufferedInputStream(response
//					.getEntity().getContent());
//			BufferedOutputStream bw = new BufferedOutputStream(
//					new FileOutputStream(newf));
//			int r;
//			while ((r = br.read()) != -1)
//				bw.write(r);
//			bw.close();
//			br.close();
//			newf.delete();
		
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {		
			e.printStackTrace();
	
		}finally{
			client.getConnectionManager().shutdown();
		}

	}
}
